package com.gimi.cloud.bbp.app.consumer.service.user.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.gimi.cloud.bbp.app.consumer.common.CheckUtil;
import com.gimi.cloud.bbp.app.consumer.feign.UserInfoFeignService;
import com.gimi.cloud.bbp.app.consumer.service.user.UserInfoService;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.JsonUtil;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.common.utils.reqhead.Util;
import com.gimi.cloud.bbp.dto.bank.BankDTO;
import com.gimi.cloud.bbp.dto.base.BaseAppDTO;
import com.gimi.cloud.bbp.dto.userInfo.PhotoFileUploadDTO;
import com.gimi.cloud.bbp.dto.userInfo.RdUserInfoDTO;

@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService{
    private static Logger logger = LoggerFactory.getLogger(UserInfoServiceImpl.class);
    @Autowired
    private UserInfoFeignService userInfoFeignService;
	@Override
	public void addUserInfo(@RequestBody String requestBody, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("请求参数===>" + JsonUtil.replaceNow(requestBody));
		RdUserInfoDTO dto = JsonUtil.jsonToBean(requestBody,RdUserInfoDTO.class);
        Util.sendResponse(userInfoFeignService.addUserInfo(dto), response);
	}

	@Override
	public void getUserInfoSingle(@RequestBody String requestBody, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("请求参数===>" + JsonUtil.replaceNow(requestBody));
		RdUserInfoDTO dtoparam = JsonUtil.jsonToBean(requestBody,RdUserInfoDTO.class);
		Util.sendResponse(userInfoFeignService.getUserInfoSingle(dtoparam), response);
	}

	@Override
	public void updateUserInfo(@RequestBody String requestBody, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("请求参数===>" + JsonUtil.replaceNow(requestBody));
		RdUserInfoDTO dto = JsonUtil.jsonToBean(requestBody,RdUserInfoDTO.class);
		dto.setUserId(Integer.valueOf(request.getHeader("userId")));
		Util.sendResponse(userInfoFeignService.updateUserInfo(dto), response);
	}

	@Override
	public void photoFileUpload(String requestData,HttpServletResponse response, HttpServletRequest request) throws IOException {
		PhotoFileUploadDTO photoFileUploadDTO = JSON.parseObject(requestData,PhotoFileUploadDTO.class);
		if (StringUtils.isBlank(photoFileUploadDTO.getFilebase())) {
			throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR,"文件BASE64编码不能为空");
		}
		if (StringUtils.isBlank(photoFileUploadDTO.getSuffix())) {
			throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR,"文件后缀名不能为空");
		}
		photoFileUploadDTO.setUserId(Integer.valueOf(request.getHeader("userId")));
		Util.sendResponse(userInfoFeignService.photoFileUpload(photoFileUploadDTO),response);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void uploadCardPhoto(HttpServletResponse response, HttpServletRequest request) {
		StandardMultipartHttpServletRequest multipartHttpServletRequest = (StandardMultipartHttpServletRequest) request;
		MultiValueMap multipartFiles = multipartHttpServletRequest.getMultiFileMap();
		List<String> typeList = new LinkedList<>();
		List<String> userIdList = new LinkedList<>();
		typeList.add(request.getParameter("type"));
		userIdList.add(request.getHeader("userId"));
		multipartFiles.put("type",typeList);
		multipartFiles.put("userId",userIdList);
		Util.sendResponse(userInfoFeignService.uploadCardPhoto(multipartFiles),response);
	}

	@Override
	public void updateUserIdInfo(String requestData, HttpServletResponse response, HttpServletRequest request) {
		logger.info("身份证更新,传入参数srcData:" + requestData);
		String userId = request.getHeader("userId");
		// 校验用户ID
		CheckUtil.checkUserId(userId, response);
		Map<String, String> requestDataMap = JsonUtil.jsonToMap(requestData);
		Map<String, String> responseDataMap =new HashMap<String,String>();
		String validDate = StringUtil.isNull(requestDataMap.get("validDate"));
/*		//请输入汉字
		if(!StringUtil.formatCN(requestDataMap.get("realName"))){
             throw new MsgException(ResponseCodeEnum.INPUT_MUST_CHINESE);
		}*/
		// 检查身份证有效时间
		CheckUtil.checkValidDate(validDate, response);

		responseDataMap.put("userId",userId);
		responseDataMap.put("sex",StringUtil.isNull(requestDataMap.get("sex")));//性别(1男,0女)
		responseDataMap.put("realName",StringUtil.isNull(requestDataMap.get("realName")));//真实姓名
		responseDataMap.put("nationality",StringUtil.isNull(requestDataMap.get("nationality")));//民族
		responseDataMap.put("birthday",StringUtil.isNull(requestDataMap.get("birthday")));//生日 格式19980203
		responseDataMap.put("address",StringUtil.isNull(requestDataMap.get("address")));//身份证住址
		responseDataMap.put("police",StringUtil.isNull(requestDataMap.get("police")));//发证机关
		responseDataMap.put("validDate",validDate);//身份证有效期
		responseDataMap.put("cardId",StringUtil.isNull(requestDataMap.get("cardId")));//身份证卡号
		responseDataMap.put("homeAddress",StringUtil.isNull(requestDataMap.get("homeAddress")));//现居住地址(省市区街道格式存入，以空格区隔)
		// 获得IP地址
		//responseDataMap.put("IP", IPUtil.getRemortIP(request));

		Util.sendResponse(userInfoFeignService.updateAppUserIdinfo(responseDataMap), response);
	}

	@Override
	public void getUserInfo(String requestData, HttpServletResponse response, HttpServletRequest request) {
		logger.info("请求参数===>" + JsonUtil.replaceNow(requestData));
		String userId = request.getHeader("userId");
		if (StringUtil.isBlank(userId)) {//验证参数合法性
			logger.error("参数错误");
			throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR);
		}
		RdUserInfoDTO dto = new RdUserInfoDTO();
		dto.setUserId(Integer.parseInt(userId));

		Util.sendResponse(userInfoFeignService.getUserInfo(dto), response);
	}

	@Override
	public void updateUserbankcard(String requestData, HttpServletResponse response, HttpServletRequest request) {
		logger.info("身份证更新,传入参数srcData:" + requestData);
		String userId = request.getHeader("userId");
		// 校验用户ID
		CheckUtil.checkUserId(userId, response);

		BankDTO bankDTO = JsonUtil.jsonToBean(requestData,BankDTO.class);
		bankDTO.setUserId(Integer.parseInt(userId));
		if(StringUtil.isBlank(bankDTO.getCardNo()) || StringUtil.isBlank(bankDTO.getCity())|| StringUtil.isBlank(bankDTO.getCounty())
				|| StringUtil.isBlank(bankDTO.getNation()) || StringUtil.isBlank(bankDTO.getPhone()) || StringUtil.isBlank(bankDTO.getCounty())
				|| StringUtil.isBlank(bankDTO.getUserName()) || StringUtil.isBlank(bankDTO.getSubBankName())){
			throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR);
		}

		Util.sendResponse(userInfoFeignService.updateUserbankcard(bankDTO), response);
	}

	@Override
	public void bankCardSign(String requestData, HttpServletResponse response, HttpServletRequest request) {
		logger.info("身份证更新,传入参数srcData:" + requestData);
		String userId = request.getHeader("userId");
		// 校验用户ID
		CheckUtil.checkUserId(userId, response);
		BankDTO bankDTO = JsonUtil.jsonToBean(requestData,BankDTO.class);
		bankDTO.setUserId(Integer.parseInt(userId));
		if (StringUtil.isEmpty(userId) || "0".equals(userId) || StringUtil.isEmpty(bankDTO.getCardNo())) {
			throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR);
		}
		Util.sendResponse(userInfoFeignService.bankCardSign(bankDTO), response);
	}

	@Override
	public void getUserBankcard(String requestData, HttpServletResponse response, HttpServletRequest request) {
		logger.info("请求参数===>" + JsonUtil.replaceNow(requestData));
		String userId = request.getHeader("userId");
		if (StringUtil.isBlank(userId)) {//验证参数合法性
			throw new MsgException(ResponseCodeEnum.SERVICE_ERROR);
		}
		RdUserInfoDTO dto = new RdUserInfoDTO();
		dto.setUserId(Integer.parseInt(userId));

		Util.sendResponse(userInfoFeignService.getUserBankcard(dto), response);
	}

	@Override
	public void updateUnimportantUserinfo(String requestData, HttpServletResponse response,
			HttpServletRequest request) {
		RdUserInfoDTO userInfo = JSON.parseObject(requestData, RdUserInfoDTO.class);
		Integer userId = null;
		try {
			userId = Integer.valueOf(request.getHeader("userId"));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("用户ID获取错误");
			throw new MsgException(ResponseCodeEnum.SERVICE_ERROR);
		}
		userInfo.setUserId(userId);
		Util.sendResponse(userInfoFeignService.updateUnimportantUserinfo(userInfo), response);
	}

	@Override
	public void getAgreement(HttpServletRequest request, HttpServletResponse response, String requestData) {
		Util.sendResponse(userInfoFeignService.getAgreement(JsonUtil.jsonToBean(requestData, BaseAppDTO.class)), response);
	}
}
